package cn.yyh.serviceOrg.service.impl;

import cn.yyh.commons.domain.LoginInfo;
import cn.yyh.commons.service.impl.MyBaseServiceImpl;
import cn.yyh.commons.utils.MD5Util;
import cn.yyh.commons.utils.StrUtils;
import cn.yyh.serviceOrg.entity.Employee;
import cn.yyh.serviceOrg.mapper.EmployeeMapper;
import cn.yyh.serviceOrg.mapper.LoginInfoMapper;
import cn.yyh.serviceOrg.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yang
 * @since 2021-07-10
 */
@Service
public class EmployeeServiceImpl extends MyBaseServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    public void save(Employee employee) {
        initEmp(employee);
        LoginInfo loginInfo = emp2LoginInfo(employee);
        loginInfoMapper.save(loginInfo);
        employee.setLoginInfoId(loginInfo.getId());
        super.save(employee);
    }

    @Override
    public void update(Employee employee) {
        initEmp(employee);
        LoginInfo loginInfo = emp2LoginInfo(employee);
        loginInfoMapper.save(loginInfo);
        super.update(employee);
    }

    @Override
    public void delete(Long id) {
        if (!ObjectUtils.isEmpty(id)) {
            super.delete(id);
            Employee byId = baseMapper.getById(id);
            if (byId != null) {
                loginInfoMapper.delete(byId.getLoginInfoId());
            }
        }

    }

    @Override
    public Employee getByLoginInfoId(Long id) {

        return baseMapper.getByLoginInfoId(id);
    }

    private void initEmp(Employee employee) {
        // 生成随机32位的盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 把密码加密
        String password = MD5Util.encrypByMd5(salt + employee.getPassword());
        employee.setSalt(salt);
        employee.setPassword(password);
    }

    private LoginInfo emp2LoginInfo(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(employee, loginInfo);
        loginInfo.setType(0);
        return loginInfo;
    }
}
